/**
 * FormController
 * 
 * @description :: Server-side logic for managing Forms
 * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {

	list : function(req, res) {
		var owner = req.session.user.userid;
		var month = req.param("current");
		var action = req.param("action");
		var dateMonth = FormService.getMonthByAction(month, action);
		
		Form.find({'owner':owner,'createdAt': { '>=': dateMonth.current.toDate(), '<': dateMonth.next.toDate() }})
		.sort('updatedAt DESC')
		.populate('type')
		.then(function findCB(result) {
			return res.view('mobile/forms/form-list', {
				forms : result,
				current : dateMonth.current.format("YYYYMM")
			});
		}).catch(function(err){
			sails.log.error(err);
			return res.serverError(err);
		});
		
	},
	
	check : function(req, res){
		var owner = req.session.user.userid;
		var noteType = sails.config.application.sysform.note;
		var month = req.param("current");
		var action = req.param("action");
		var dateMonth = FormService.getMonthByAction(month, action);
		
		Form.find({'waitChecker':owner, 'updatedAt': { '>=': dateMonth.current.toDate(), '<': dateMonth.next.toDate() }})
		.sort('updatedAt DESC')
		.populate('owner')
		.then(function findCB(result) {
			return res.view('mobile/forms/form-check', {
				forms : result,
				current : dateMonth.current.format("YYYYMM")
			});
			
		}).catch(function(err){
			sails.log.error(err);
			return res.serverError(err);
		});
	},
	
	doCheck : function(req, res){
		
		var json = req.body;
		var form = json.form;
		var opinion = json.opinion;
		//var url = json.url;
		var url = sails.config.application.appPath;
		
		FormOpinion.create(json.opinion)
		.then(function findCB(result) {
			
			Form.update({'id':form.id}, form)
			.then(function (forms) {
				if(forms[0].state == 3){
					if(forms[0].note != undefined){
						LeaveNote.findOne(forms[0].note)
						.then(function (note) {
							if(note.type == sails.config.application.vacationType){
								Vacation.findOne({'owner':forms[0].owner})
								.then(function (vaca) {
									Vacation.update(vaca.id, {'hours':(parseInt(vaca.hours) - parseInt(note.hours))})
									.then(function (form) {
										WechatService.sendFormToOwner(forms[0], url, req, function(err, result){});
										return res.send({success : true});
									});
								});
							}else{
								return res.send({success : true});
							}
						});
					}else{
						WechatService.sendFormToOwner(forms[0], url, req, function(err, result){});
						return res.send({success : true});
					}
				}else{
					return res.send({success : true});
				}
			});
			
		}).catch(function(err){
			sails.log.error(err);
			return res.send({
				success : false,
				error : err
			});
		});
	},
	
	get : function(req, res){
		
		var method = req.param("method");
		var resview = 'mobile/forms/form-create';
		
		if(method == 'update' || method == 'detail'){
			var pkid = req.param("pkid");
			
			//Form
			Form.findOne({'id' : pkid})
			.populate('owner')
			.populate('propvals')
			.populate('attachments')
			.then(function (form){
				
				//FormType
				FormType.findOne({'id' : form.type})
				.populate('props',{'sort' : 'seq ASC'})
				.then(function (formType){
					
					//FormOpinion
					FormOpinion.find({'form':form.id})
					.sort('updatedAt DESC')
					.populate('superior')
					.then(function (opinions){
						
						if(method == 'detail'){
							resview = 'mobile/forms/form-detail';
							
						}else if(method == 'update'){
							//resview = 'mobile/forms/form-update';
						}
						form.opinions = opinions;
						
						return res.view(resview, {
							formType : formType,
							form : form
						});
						
					});
					
				});
				
			}).catch(function(err){
				sails.log.error(err);
				return res.serverError(err);
			});
		}else{
			
			var typeid = req.param('type');
			FormType
			.findOne({'id' : typeid})
			.populate('props')
			.then(function findOneCB(formType){
				return res.view(resview, {
					formType : formType,
				});
				
			}).catch(function(err){
				sails.log.error(err);
				return res.serverError(err);
			});
		}
		
	},
	
	select : function(req, res){
		FormType
		.find({'system':false})
		.sort('seq ASC')
		.then(function findCB(results) {
			return res.view('mobile/forms/form-select', {
				formTypes : results,
			});
		}).catch(function(err){
			sails.log.error(err);
			return res.serverError(err);
		});
	},
	
	send : function(req, res){

		var pkid = req.body.pkid;
		var userid = req.body.user;
		//var url = req.body.url;
		var url = sails.config.application.appPath;
		
		Form.update({'id':pkid}, {'waitChecker':userid, 'lastChecker':null,'state':2})
		.then(function (forms) {
			if(forms.length > 0){
				WechatService.sendFormToChecker(forms[0], url, req, function(err, result){
					if(result.errcode == 0){
						return res.send({success : true});
					}else{
						return res.send({
							success : false,
							error : err
						});
					}
				});
			}
		}).catch(function(err){
			sails.log.error(err);
			return res.send({
				success : false,
				error : err
			});
		});
	},
	
};
